# -*- coding: utf-8 -*-
import arcpy,datetime,os,sys,json,multiprocessing
import pandas as pd
import numpy as np

def setStrDefaultEncoding():
	reload(sys)
	sys.setdefaultencoding('utf8')
	print '{}sys getdefaultencoding: {}{}'.format('\n',sys.getdefaultencoding(),'\n','\n')

def init(l):
	global lock
	lock = l

def rings2shp(rowsdict, i):
	try:
		setStrDefaultEncoding()
		dir_name = os.getcwd().decode(sys.getfilesystemencoding())
		fcname = u'国土调查云分斑'
		spatial_reference = arcpy.SpatialReference(4490)
		gdbpath = dir_name + u'/国土调查云分斑{}.gdb'.format(i)
		fcpath = gdbpath + '/' + fcname
		arcpy.CreateFileGDB_management(dir_name, u'/国土调查云分斑{}.gdb'.format(i))
		arcpy.CreateFeatureclass_management(gdbpath, out_name=fcname, geometry_type='POLYGON', spatial_reference=spatial_reference)

		field_info_list = []
		fieldk = []
		for k,v in rowsdict[0].items():
			if k != 'shape':
				field_info_list.append((k.decode('utf-8'), u'text'))
				fieldk.append(k)
		
		for field in field_info_list:
			if field[1] == u'text':
				arcpy.AddField_management(fcpath, field[0], field[1], '', '', 255)
			else:
				arcpy.AddField_management(fcpath, field[0], field[1])

		for row in rowsdict:
			if pd.isna(row['shape']):
				continue
			a = json.loads(row['shape'])['rings']
			if len(a) > 1:
				with arcpy.da.InsertCursor(fcpath, ['SHAPE@']+fieldk) as i_cur:
					features = []
					for p in a:
						arcpy_point_list = [arcpy.Point(pt[0], pt[1]) for pt in p]
						polygon_array = arcpy.Array(arcpy_point_list)
						features.append(polygon_array)
					polygon_geometry_array = arcpy.Array(features)
					polygon_geometry = arcpy.Polygon(polygon_geometry_array, spatial_reference)
					insert_row1 = [polygon_geometry]
					for kk in fieldk:
						insert_row1 = insert_row1 + [str(row[kk])]
					i_cur.insertRow(insert_row1)
			elif len(a) == 1:
				with arcpy.da.InsertCursor(fcpath, ['SHAPE@']+fieldk) as i_cur:
					arcpy_point_list = [arcpy.Point(pt[0], pt[1]) for pt in a[0]]
					polygon_array = arcpy.Array(arcpy_point_list)
					polygon_geometry = arcpy.Polygon(polygon_array, spatial_reference)
					insert_row1 = [polygon_geometry]
					for kk in fieldk:
						insert_row1 = insert_row1 + [str(row[kk])]
					i_cur.insertRow(insert_row1)
		lock.acquire()
		print u'rings2shp fnc end: {}'.format(i)
		lock.release()
	except Exception as err:
		lock.acquire()
		print 'rings2shp fnc err: ', err
		lock.release()

def main():
	try:
		splitn = 4
		split_dt = pd.read_csv(u'XXX项目清单_20231222212129.csv', dtype=str).copy()
		split_dts = np.array_split(split_dt, splitn)

		cpucore = multiprocessing.cpu_count()
		mylock = multiprocessing.Lock()
		mpool = multiprocessing.Pool(cpucore, initializer = init, initargs = (mylock, ))

		for i in range(splitn):
			sdt = split_dts[i].to_dict(orient='records')
			mpool.apply_async(rings2shp, args=(sdt, i, ))

		print '{}mpool start here.{}'.format('\n', '\n')
		mpool.close()
		mpool.join()
		print 'mpool end here.{}'.format('\n')
	except Exception as err:
		print 'main err: ', err

if __name__ == '__main__':
	time1 = datetime.datetime.now()
	print 'start time: ', time1
	setStrDefaultEncoding()
	main()
	time2 = datetime.datetime.now()
	print 'end time: ', time2
	print 'total time: ', time2 - time1